import random

from django.core.paginator import Paginator
from django_redis import get_redis_connection

from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.utils import jwt_decode_handler

from apps.food.models import Foods, FoodCategory
from apps.serializers.food_serializers import RecommendSerializer
from apps.uitls.token import Verify
from apps.user.models import UserComment, UserCommentLike


class Detail(APIView):
    def get(self, request):
        code = request.GET.get("code")
        food = Foods.objects.filter(id=code)
        if not food:
            return
        food = food[0]
        buredens = []
        for i in food.dosing_set.all():
            buredens.append({"burdensName": i.name, "burdensContent": i.num})
        # 因为小程序下方的按钮挡住了最后一列数据，所以用空数据填充，以后修改小程序可以将下面一行代码删除
        # buredens.append({"burdensName": "", "burdensContent": ""})

        makes = []
        for i in food.methodofwork_set.all():
            makes.append({"isIndex": i.sequence, "info": i.titles, "imgUrl": i.default_image})
        data = {
            "caipuName": food.name, "imgUrl": food.default_image,
            "healthStr": food.title,
            "buredens": buredens,
            "makes": makes
        }
        res = {"status": 200, "data": data}
        # 保存用户浏览数据
        redis_conn = get_redis_connection('default')
        pl = redis_conn.pipeline()
        try:
            user = Verify(request.META.get("HTTP_JWT"))
        except:
            user = False
        if user:
            user_id = user.get("user_id")
            # 先去重
            pl.lrem('history_%s' % user_id, 0, code)
            # 再存储
            pl.lpush('history_%s' % user_id, code)
            # 最后截取
            pl.ltrim('history_%s' % user_id, 0, 10)
            # 执行管道
            pl.execute()
        return Response(res)


class Recommend(ListAPIView):
    # 指定序列化器类
    serializer_class = RecommendSerializer

    # 注：关闭分页
    pagination_class = None

    def get_queryset(self):
        """返回视图所使用的查询集"""
        # 获取pk
        pk = self.kwargs['pk']
        # 获取当前菜品的数据
        food = Foods.objects.filter(id=pk)

        lists = []
        # 判断同一类的食物是否超过4个，如果超过4个推荐的数据则是从这些数据中随机取4个
        if len(FoodCategory.objects.filter(category_id=food[0].foodcategory_set.all()[0].category.id)) > 3:
            a = random.sample(
                range(0, len(FoodCategory.objects.filter(category_id=food[0].foodcategory_set.all()[0].category.id))),
                4)
            for i in a:
                lists.append(
                    FoodCategory.objects.filter(category_id=food[0].foodcategory_set.all()[0].category.id)[i].food_id)
        # 如果同一种食物不超过4个则将同一种分类的食物全部当做推荐的数据返回
        else:
            for i in FoodCategory.objects.filter(category_id=food[0].foodcategory_set.all()[0].category.id):
                lists.append(i.food_id)
        return Foods.objects.filter(id__in=lists)


class ListByCategory(APIView):
    def get(self, request, pk):

        page = int(request.GET.get("page", 1))
        if page == 0:
            page = 1
        category = FoodCategory.objects.filter(category_id=pk)
        # 创建分页器
        paginator = Paginator(category, 5)

        # 判断页数是否大于总页数
        if page > paginator.num_pages:
            page = paginator.num_pages
        # 获取数据
        page_food = paginator.page(page)

        lists = []
        for i in page_food:
            lists.append(
                {"id": i.food.id, "default_image": i.food.default_image, "name": i.food.name, "title": i.food.title})
        return Response(data={"lists": lists, "pages": paginator.num_pages})


class ListByKeyName(ListAPIView):
    # 指定序列化器类
    serializer_class = RecommendSerializer

    def get_queryset(self):
        name = self.request.GET.get("keywords")
        print(self.request.GET.get("page"))
        if not name:
            name = "肉"
        return Foods.objects.filter(name__contains=name)


class FoodComment(APIView):
    def get(self, request, pk):
        token = request.META.get("HTTP_JWT")
        if token:
            try:
                user = jwt_decode_handler(token)
            except:
                return Response({"status": 402, "data": "token过期了"})

        comment = UserComment.objects.filter(food_id=pk, is_child=None)
        commentlist = []
        for i in comment:
            child = []
            T_F = False
            if UserCommentLike.objects.filter(user_id=user.get("user_id"), comment=i, is_del=False):
                T_F = True
            num = UserCommentLike.objects.filter(comment=i, is_del=False).count()
            if i.usercomment_set.all():
                # 判断是否有子评论，如果有则循环获取
                for j in i.usercomment_set.all():
                    t_f = False
                    if UserCommentLike.objects.filter(user_id=user.get("user_id"), comment=j, is_del=False):
                        t_f = True
                    nums = UserCommentLike.objects.filter(comment=j, is_del=False).count()
                    child.append({"id": j.id, "avatar": j.user.user_img,
                                  "username": j.user.username, "content": j.comment,
                                  "add_time": str(j.update_time)[:16], "like": nums, "is_like": t_f
                                  })
            commentlist.append({"id": i.id, "avatar": i.user.user_img,
                                "username": i.user.username, "content": i.comment, "add_time": str(i.update_time)[:16],
                                "like": num, "child": child, "is_like": T_F,
                                })
        # commentlist = [
        #     {"id": 1, "avatar": "https://i5.meishichina.com/data/avatar/009/08/83/92_avatar_big.jpg?x-oss-process=style/c320&v=2020031710",
        #      "username": "laowang", "content": "66666, nb", "add_time": 2019, "like": 1, "chils": [
        #         {"id": 1,
        #          "avatar": "https://i5.meishichina.com/data/avatar/009/08/83/92_avatar_big.jpg?x-oss-process=style/c320&v=2020031710",
        #          "username": "laowang", "content": "66666, nb", "add_time": 2019, "like": 1,
        #          },
        #     ]
        #      },
        #     {"id": 1,
        #      "avatar": "https://i5.meishichina.com/data/avatar/006/62/88/24_avatar_big.jpg?x-oss-process=style/c320&v=2020022302",
        #      "username": "laowang", "content": "66666, nb", "add_time": 2019, "like": 1},
        #     {"id": 1,
        #      "avatar": "https://i5.meishichina.com/data/avatar/006/62/88/24_avatar_big.jpg?x-oss-process=style/c320&v=2020022302",
        #      "username": "laowang", "content": "66666, nb", "add_time": 2019, "like": 1},
        #
        # ]
        return Response({"status": 0, "commentlist": commentlist})

    def post(self, requst, pk):
        print(requst.data)
        food_id = requst.data.get("code")
        content = requst.data.get("content")
        token = requst.data.get("jwt")
        reply = requst.data.get("reply")
        print(food_id, content, token)
        if not all([token, content, food_id]):
            return
        try:
            user = jwt_decode_handler(token)
        except:
            return Response({"status": 0, "data": "token过期了"})
        if not reply:
            user_comment = UserComment(food_id=food_id, comment=content, user_id=user.get("user_id"))
        else:
            user_comment = UserComment(food_id=food_id, comment=content, user_id=user.get("user_id"), is_child_id=reply)
        user_comment.save()

        return Response({"status": 0, "data": "添加评论成功"})


class FoodCommentLike(APIView):
    # permission_classes = [IsAdminUser]

    def post(self, request, pk):
        print(request.data, pk)
        token = request.data.get("jwt")
        try:
            user = jwt_decode_handler(token)
        except:
            return Response({"status": 402, "data": "token过期了"})

        userlike = UserCommentLike.objects.filter(comment_id=pk, user_id=user.get("user_id"))
        data = {}
        print(user)
        print(user.get("user_id"))
        if userlike:
            if userlike[0].is_del:
                userlike[0].is_del = False
                userlike[0].save()
                data["msg"] = "点赞成功"
                data["status"] = 0
            else:
                userlike[0].is_del = True
                userlike[0].save()
                data["msg"] = "取消点赞成功"
                data["status"] = 0
        else:
            like = UserCommentLike(comment_id=pk, user_id=user.get("user_id"))
            like.save()
            data["msg"] = "点赞成功"
            data["status"] = 1
        return Response(data)
